"""
通用权限管理模块
提供项目中常用的权限类
"""
from rest_framework import permissions


class IsOwnerOrReadOnly(permissions.BasePermission):
    """所有者或只读权限"""

    def has_object_permission(self, request, view, obj):
        # 安全的方法（GET、HEAD、OPTIONS）允许所有请求
        if request.method in permissions.SAFE_METHODS:
            return True

        # 写操作需要所有者权限
        if hasattr(obj, 'owner'):
            return obj.owner == request.user or request.user.is_superuser
        elif hasattr(obj, 'creator'):
            return obj.creator == request.user or request.user.is_superuser
        elif hasattr(obj, 'user'):
            return obj.user == request.user or request.user.is_superuser

        return request.user.is_superuser


class IsTeacherOrAdmin(permissions.BasePermission):
    """教师或管理员权限"""

    def has_permission(self, request, view):
        # 检查用户是否已认证且是教师或管理员
        if not request.user.is_authenticated:
            return False

        return (
            request.user.is_staff or
            request.user.is_superuser or
            getattr(request.user, 'is_teacher', False) or
            getattr(request.user, 'is_admin_user', False)
        )


class IsAdminOrReadOnly(permissions.BasePermission):
    """管理员或只读权限"""

    def has_permission(self, request, view):
        # 安全的方法（GET、HEAD、OPTIONS）允许所有请求
        if request.method in permissions.SAFE_METHODS:
            return True

        # 写操作需要管理员权限
        return (
            request.user.is_authenticated and (
                request.user.is_staff or
                request.user.is_superuser
            )
        )


class IsStudent(permissions.BasePermission):
    """学生权限"""

    def has_permission(self, request, view):
        # 检查用户是否已认证且是学生
        if not request.user.is_authenticated:
            return False

        return getattr(request.user, 'is_student', False)


class IsStaffOrReadOnly(permissions.BasePermission):
    """员工或只读权限"""

    def has_permission(self, request, view):
        # 安全的方法（GET、HEAD、OPTIONS）允许所有请求
        if request.method in permissions.SAFE_METHODS:
            return True

        # 写操作需要员工权限
        return (
            request.user.is_authenticated and (
                request.user.is_staff or
                request.user.is_superuser
            )
        )


class IsSuperuserOnly(permissions.BasePermission):
    """仅超级用户权限"""

    def has_permission(self, request, view):
        # 仅超级用户可以访问
        return (
            request.user.is_authenticated and
            request.user.is_superuser
        )